package com.ycc.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ycc.pojo.Cart;
import com.ycc.pojo.CartItem;
import com.ycc.pojo.Content;
import com.ycc.pojo.Money;
import com.ycc.service.impl.ContentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 购物车
 * @Author: ycc
 * @Date: 2021/6/27 9:31
 */
@Controller
public class CartController {
    @Autowired
    private ContentServiceImpl contentService;
    @Autowired
    RedisTemplate redisTemplate;
    private static final String CART_KEY = "cart:user:";

    //添加购物车
    @RequestMapping("/add/{id}")
    public String addCart(Integer buyNumber, @PathVariable("id")String id, ModelMap modelMap) throws JsonProcessingException {
        ///获取登录的用户信息
        User user = (org.springframework.security.core.userdetails.User)
                SecurityContextHolder
                        .getContext()
                        .getAuthentication()
                        .getPrincipal();
        ///用户名称(key)
        String username = user.getUsername();
        ///集合内容为添加商品信息，即：
        ///cart:user:username [contentId amount]
        String key = CART_KEY + username;
        Boolean hasKey = redisTemplate.opsForHash().getOperations().hasKey(key);
        if (hasKey){
            this.redisTemplate.opsForHash().put(key,id,buyNumber);
        }else {
            this.redisTemplate.opsForHash().put(key,id,buyNumber);
            this.redisTemplate.expire(key,90, TimeUnit.DAYS);
        }

        ///此时添加成功，界面不变动
        Content content = (Content) contentService.selectById(id);
        List<Content> list = new ArrayList<>();
        list.add(content);
        modelMap.addAttribute("good", list);
        return "watch";
    }

    //更新购买数量
    @RequestMapping("/update/{id}")
    public String updateCart(Integer buyNumber, @PathVariable("id")String id, ModelMap modelMap) throws JsonProcessingException {
        ///获取登录的用户信息
        User user = (org.springframework.security.core.userdetails.User)
                SecurityContextHolder
                        .getContext()
                        .getAuthentication()
                        .getPrincipal();
        ///用户名称(key)
        String username = user.getUsername();
        ///集合内容为添加商品信息，即：
        ///cart:user:username [contentId amount]
        String key = CART_KEY + username;
        Boolean hasKey = redisTemplate.opsForHash().getOperations().hasKey(key);
        if (hasKey){
            ////如果订单存在：执行删除或者更新
            ///如果数量格内为填写，为删除
            if (buyNumber==null){
                ///删除
                this.redisTemplate.opsForHash().delete(key,id);
            }else {
                ///更新
                this.redisTemplate.opsForHash().put(key,id,buyNumber);
            }
        }else {
            System.out.println("订单未找到，修改失败");
        }
        return "redirect:/cart";
    }

    //进入个人购物车，查看全部
    @RequestMapping("/cart")
    String cart(ModelMap modelMap) {
        ///获取登录的用户信息
        User user = (org.springframework.security.core.userdetails.User)
                SecurityContextHolder
                        .getContext()
                        .getAuthentication()
                        .getPrincipal();
        String username = user.getUsername();
        String key = CART_KEY + username;
        Map<String,Integer> map = this.redisTemplate.opsForHash().entries(key);
        List<Cart> cartList = new ArrayList<>();
        for(Map.Entry<String,Integer> entry : map.entrySet()){
            Cart cart = new Cart();
            cart.setUsername(username);
            cart.setContentId(entry.getKey());
            cart.setAmount(entry.getValue());
            cartList.add(cart);
        }
        modelMap.addAttribute(cartList);
        return "cart";
    }

    //去支付
    @RequestMapping("/gotoPay")
    public String gotoPay(ModelMap modelMap){
        Double totalMoney = 0.0;
        ///获取登录的用户信息
        User user = (org.springframework.security.core.userdetails.User)
                SecurityContextHolder
                        .getContext()
                        .getAuthentication()
                        .getPrincipal();
        String username = user.getUsername();
        String key = CART_KEY + username;
        Map<String,Integer> map = this.redisTemplate.opsForHash().entries(key);
        List<Cart> cartList = new ArrayList<>();
        for(Map.Entry<String,Integer> entry : map.entrySet()){
            Cart cart = new Cart();
            cart.setUsername(username);
            cart.setContentId(entry.getKey());
            cart.setAmount(entry.getValue());
            cartList.add(cart);
        }

        for(Cart cart : cartList){
            Integer amount = cart.getAmount();
            Content content = this.contentService.selectById(cart.getContentId());
            Double price = content.getPrice();
            Double total = amount*price;
            totalMoney += total;
        }
        List<Money> money = new ArrayList<>();
        Money money1 = new Money(totalMoney);
        money.add(money1);
        modelMap.addAttribute(money);
        return "myPay";
    }

}
